const net = require('net');
const fs = require('fs');
const path = require('path');
const server = net.createServer();

// 监听端口
server.listen(9527);

server.on('listening', () => {
    console.log('监听端口成功')
})

// 浏览器访问 http://127.0.0.1:9527/
server.on('connection', socket => {
    console.log('有请求进来')

    socket.on('data', async chunk => {
        console.log('客户端写入的数据:', chunk.toString('utf-8'))
        // Referer 对应完整路径 可提取路径

        // 服务器写入内容 响应
        // socket.write('响应内容') // 不符合 http 格式 服务器无法分析
        // 响应 文本
        // responseText(socket)

        // 响应图片
        await responseImg(socket)


        // 关闭双工流 服务器主动断开链接
        socket.end()
    })

    socket.on('close', () => {
        console.log('连接关闭')
    })
})

async function responseImg(socket) {
    const filename = path.resolve(__dirname, './xyz.jpg')
    // 不能有空格
    const headBuffer = Buffer.from(`HTTP/1.1 200 OK
Content-Type: text/plain;charset=utf-8

`, 'utf-8')
    const bodyBuffer = await fs.promises.readFile(filename)

    const result = Buffer.concat([headBuffer, bodyBuffer])

    socket.write(result)
}


function responseText(socket) {
    socket.write(`HTTP/1.1 200 OK
Content-Type: text/plain;charset=utf-8

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title></title>
  </head>
  <body>
  响应内容
  </body>
</html>
`)
}